package light.head.controller.inv;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.inv.InvAllocateDAO;
import light.head.dao.inv.InvAllocateDetailDAO;
import light.head.dao.inv.InvAllocateItemDAO;
import light.head.dao.inv.InvBillConfingDAO;
import light.head.dao.inv.InvDepotDAO;
import light.head.dao.inv.InvInStorageDAO;
import light.head.dao.inv.InvInStorageDetailDAO;
import light.head.dao.inv.InvInStorageItemDAO;
import light.head.dao.inv.InvOutStorageDAO;
import light.head.dao.inv.InvOutStorageDetailDAO;
import light.head.dao.inv.InvOutStorageItemDAO;
import light.head.dao.inv.InvStorageDAO;
import light.head.dao.inv.InvStorageDetailDAO;
import light.head.dao.sys.OrganDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.inv.InvAllocate;
import light.head.model.inv.InvAllocateDetail;
import light.head.model.inv.InvAllocateItem;
import light.head.model.inv.InvInStorage;
import light.head.model.inv.InvInStorageDetail;
import light.head.model.inv.InvInStorageItem;
import light.head.model.inv.InvOutStorage;
import light.head.model.inv.InvOutStorageDetail;
import light.head.model.inv.InvOutStorageItem;
import light.head.model.inv.InvStorage;
import light.head.model.inv.InvStorageDetail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = Url.C_INVALLOCATE)
public class InvAllocateController extends SupporterController{
	private InvAllocateDAO iaDAO;
	private InvAllocateItemDAO iaiDAO;
	private InvAllocateDetailDAO iadDAO;
	private InvStorageDAO isDAO;
	private InvStorageDetailDAO detailDAO;
	private InvDepotDAO idDAO;
	private InvInStorageDAO iisDAO;
	private InvInStorageItemDAO iisiDAO;
	private InvInStorageDetailDAO iisdDAO;
	private InvOutStorageDAO iosDAO;
	private InvOutStorageItemDAO iosiDAO;
	private InvOutStorageDetailDAO iosdDAO;
	private InvBillConfingDAO ibcfDAO;
	private OrganDAO organDAO;
	
	
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request,HttpServletResponse response) throws Exception{
		return new ModelAndView(Url.INVALLOCATE_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query (HttpServletRequest request, HttpServletResponse response) throws Exception{
		PageBean pb = createPageBean(request);
		Map<String,String> map = createQueryMapByParmName(request, Parm.DELETED,Parm.TIME1,Parm.TIME2,Parm.DNAME,Parm.CNAME,Parm.DN,Parm.CN);
		if (iaDAO.findByMap(organDAO.getSonCodeList(cu_organCode(request)), map, pb) == RESULT.SUCCESS) {
			InvAllocate ia =null;
			for (Object o : pb.getResultList()) {
				ia = (InvAllocate) o;
				ia.setItemList(iaiDAO.findIac(ia.getCode()));
			}
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.INVALLOCATE_LIST);
	}
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if (null != code) {
			InvAllocate is = iaDAO.get(Integer.parseInt(code));
			request.setAttribute(Parm.ALLOCATE, is);
		} 
		return new ModelAndView(Url.INVALLOCATE_EDIT);
	}
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if (null != code) {
			InvAllocate ia = iaDAO.get(Integer.parseInt(code));
			List<InvAllocateItem> itemList = iaiDAO.findIac(ia.getCode());
			ia.setItemList(itemList);
			for (InvAllocateItem item : itemList) {
				List<InvAllocateDetail> detailList = iadDAO.findIaic(item.getCode());
				item.setDetailList(detailList);
			}
			request.setAttribute(Parm.ALLOCATE, ia);
		} 
		return new ModelAndView(Url.INVALLOCATE_DETAIL);
	}
	@RequestMapping(value = Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		InvAllocate ia = iaDAO.get(Integer.parseInt(code));
		if (null == ia) {
			print(response, Msg.NOT_FIND);
			return;
		}
		ia.setDeleted(true);
		if (isDAO.upd(ia) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		InvAllocate ia = iaDAO.get(Integer.parseInt(code));
		if (null == ia) {
			print(response, Msg.NOT_FIND);
			return;
		}
		ia.setDeleted(false);
		if (isDAO.upd(ia) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	
	@Transactional
	@RequestMapping(value = Url.SAVE)
	public void save (InvAllocate ia, HttpServletRequest request, HttpServletResponse response) throws Exception{
		RESULT result = RESULT.ERROR;
		List<InvAllocateItem> itemList = ia.getItemList();
		//保存调拨信息
		ia.setDn(ibcfDAO.createBCode(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_SEVEN));
		ia.setCu(cu_code(request));
		ia.setCt(new Date());
		ia.setOc(cu_organCode(request));
		ia.setDeleted(false);
		result = iaDAO.add(ia);
		
		for (InvAllocateItem item : itemList) {
			if (item != null && item.getCc() != null && item.getCount() != null){
				//保存调拨明细
				item.setDeleted(false);
				item.setIac(ia.getCode());
				iaiDAO.add(item);
				Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
				String serial = detailDAO.findByCcOc(item.getCc(), organDAO.getSonCodeList(oc));
				if(item.getSnc() == 3){
					for (InvAllocateDetail detail : item.getDetailList()) {
						if (detail != null && detail.getSerial() != null) {
							// 保存 调拨详情
							detail.setIaic(item.getCode());
							detail.setDeleted(false);
							result = iadDAO.add(detail);
						}
					}
				} else if(item.getSnc() == 2 && serial != null) {
					InvAllocateDetail detail = new InvAllocateDetail();
					// 保存 调拨详情
					detail.setIaic(item.getCode());
					detail.setDeleted(false);
					detail.setSerial(serial);
					result = iadDAO.add(detail);
				}
			}	
		}	
		if (result == RESULT.SUCCESS){
			print(response, Msg.SUCCESS);
		}
	}
	
	// 确认调拨
	@Transactional
	@RequestMapping(Url.IN)
	public void in(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception { 
		RESULT result = RESULT.ERROR;
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		InvAllocate ia = iaDAO.get(code);
		List<InvAllocateItem> itemList = iaiDAO.findIac(ia.getCode());
		//保存入库信息
		InvInStorage iis = new InvInStorage();
		iis.setCt(new Date());
		iis.setCu(ia.getCu());
		iis.setDeleted(false);
		iis.setDn(ibcfDAO.createBCode(oc, Sys.B_THREE));
		iis.setOc(ia.getIoc());
		iis.setType(Sys.B_ONE);
		result = iisDAO.add(iis);
		//保存出库信息
		InvOutStorage ios = new InvOutStorage();
		ios.setCt(new Date());
		ios.setCu(ia.getCu());
		ios.setDeleted(false);
		ios.setDn(ibcfDAO.createBCode(oc, Sys.B_FOUR));
		ios.setOc(ia.getOc());
		ios.setType(Sys.B_THREE);
		result = iosDAO.add(ios);
		if (result != RESULT.SUCCESS) return;
		for (InvAllocateItem item : itemList) {
			if (item != null && item.getCc() != null && item.getCount() != null){
				List<InvAllocateDetail> detailList = iadDAO.findIaic(item.getCode());
				//保存出库明细
				InvOutStorageItem iosi = new InvOutStorageItem();
				iosi.setCc(item.getCc());
				iosi.setDc(ia.getOdc());
				iosi.setDeleted(false);
				iosi.setIosc(ios.getCode());
				iosi.setNumber(item.getCount());
				iosi.setPrice(item.getPrice());
				iosi.setSnc(item.getSnc());
				result = iosiDAO.add(iosi);
				//修改出库仓库存数量
				List<InvStorage> db1List = isDAO.findByCcDc(item.getCc(), ia.getOdc(), ia.getOc());
				if(db1List != null && db1List.size() > 0){
					if (db1List.get(0).getCount().intValue() == 0 ) {
						print(response, Msg.EXISTS);
						return;
					}if (db1List.get(0).getCount().intValue() < item.getCount()) {
						print(response, Msg.NOT_FIND);
						return;
					}
					db1List.get(0).setCount(db1List.get(0).getCount() - item.getCount());
					result = isDAO.upd(db1List.get(0));
					//删除库存详情
					if (detailList != null && detailList.size() > 0) {
						for(InvAllocateDetail iad : detailList){
							if (iad != null && iad.getSerial() != null){
								if(item.getSnc() == 3){
									List<InvStorageDetail> isdList = detailDAO.findByOc(iad.getSerial(), organDAO.getSonCodeList(oc));
									if (null != isdList && isdList.size() > 0){
										result = detailDAO.del(isdList.get(0));	
									}
								}
							}
						}
					}
				}
				//保存入库明细
				InvInStorageItem iisi = new InvInStorageItem();
				iisi.setCc(item.getCc());
				iisi.setDc(ia.getIdc());
				iisi.setDeleted(false);
				iisi.setIisc(iis.getCode());
				iisi.setNumber(item.getCount());
				iisi.setPrice(item.getPrice());
				iisi.setSnc(item.getSnc());
				result = iisiDAO.add(iisi);
				//修改入库仓库存数量
				List<InvStorage> dbList = isDAO.findByCcDc(item.getCc(), ia.getIdc(), ia.getIoc());
				if(dbList != null && dbList.size() > 0){
					dbList.get(0).setCount(dbList.get(0).getCount() + item.getCount());
					result = isDAO.upd(dbList.get(0));
					//保存库存详情
					if (detailList != null && detailList.size() > 0) {
						for(InvAllocateDetail iad : detailList){
							if(item.getSnc() == 3){
								InvStorageDetail isd = new InvStorageDetail();
								isd.setDeleted(false);
								isd.setIsc(dbList.get(0).getCode());
								isd.setSerial(iad.getSerial());
								result = detailDAO.add(isd);
							}
						}
					}
				}else {
					InvStorage is = new InvStorage();
					is.setCc(item.getCc());
					is.setCount(item.getCount());
					is.setDc(ia.getIdc());
					is.setDeleted(false);
					is.setOc(ia.getIoc());
					is.setPrice(item.getPrice());
					is.setSnc(item.getSnc());
					result = isDAO.add(is);
					if (result != RESULT.SUCCESS) return;
					if (detailList != null && detailList.size() > 0) {
						for(InvAllocateDetail iad : detailList){
							InvStorageDetail isd = new InvStorageDetail();
							isd.setDeleted(false);
							isd.setIsc(is.getCode());
							isd.setSerial(iad.getSerial());
							result = detailDAO.add(isd);
						}
					}
				}
				if (result != RESULT.SUCCESS) return;
				if (detailList != null && detailList.size() > 0) {
					for(InvAllocateDetail iad : detailList){
						//保存入库详情
						InvInStorageDetail iisd = new InvInStorageDetail();
						iisd.setDeleted(false);
						iisd.setIisic(iisi.getCode());
						iisd.setSerial(iad.getSerial());
						result = iisdDAO.add(iisd);
						if (result != RESULT.SUCCESS) return;
						//保存出库详情
						InvOutStorageDetail iosd = new InvOutStorageDetail();
						iosd.setDeleted(false);
						iosd.setIosic(iosi.getCode());
						iosd.setSerial(iad.getSerial());
						result = iosdDAO.add(iosd);
					}
				}
			}
		}
		if (result == RESULT.SUCCESS){
			ia.setCvc(cu_code(request));
			ia.setCvt(new Date());
			ia.setVerify(true);
			result = iaDAO.upd(ia);
		}
		if (result == RESULT.SUCCESS){
			print(response, Msg.SUCCESS);
		}
	}
	
	/**
	 * 查询库存商品
	 */
	@RequestMapping(Url.S_INIT)
	public ModelAndView sInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.INDEX, request.getParameter(Parm.INDEX));
		request.setAttribute(Parm.DC, request.getParameter(Parm.DC));
		return new ModelAndView(Url.INVALLOCATE_S_INIT);
	}
	
	@RequestMapping(Url.S_LIST)
	public ModelAndView sList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME,Parm.FAST);
		String  a = request.getParameter(Parm.DC);
		if (RESULT.SUCCESS == isDAO.findByMap_2(Integer.parseInt(a),organDAO.getSonCodeList(cu_organCode(request)),map,pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.INVALLOCATE_S_LIST);
	}
  
	/**
	 * 查询仓库
	 */
	@RequestMapping(Url.AID_INIT_1)
	public ModelAndView aidInit1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.PIB, request.getParameter(Parm.PIB));
		System.out.println(request.getParameter(Parm.PIB));
		return new ModelAndView(Url.INVALLOCATE_AID_INIT1);
	}
	
	@RequestMapping(Url.AID_LIST_1)
	public ModelAndView aidList1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME);
		String dc = request.getParameter(Parm.PIB);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (isNotNull(dc) 
				&& dc.equals("1")){
			if (RESULT.SUCCESS == idDAO.findByMap(cu_organCode(request), map,pageBean)) {
				request.setAttribute(Parm.PAGE_BEAN, pageBean);
			}
		}else if(isNotNull(dc) 
				&& dc.equals("2")){
			if (RESULT.SUCCESS == idDAO.findByMap(organDAO.getSonCodeList(oc), map,pageBean)) {
				request.setAttribute(Parm.PAGE_BEAN, pageBean);
			}
		}
		return new ModelAndView(Url.INVALLOCATE_AID_LIST1);
	}
	//判断序列号是否是该库存下的商品所属
	@RequestMapping(value = Url.VERIFY2)
	public void serial2(HttpServletRequest request, HttpServletResponse response)throws Exception {
		String serial = request.getParameter("serial");
		String cc = request.getParameter("cc");
		String dc = request.getParameter("dc");
		List<InvStorageDetail> detailList = detailDAO.findBySerialCcDc(serial,Integer.parseInt(cc),Integer.parseInt(dc));
		if (detailList != null && detailList.size() > 0) {
			print(response, Msg.SUCCESS);
			
		} else {
			print(response, Msg.ERROR);
			return;
		}
	}
	
	// 用序列号到库存查询出对应的商品信息
	@RequestMapping(value = Url.VERIFY)
	public void loadCommodity(HttpServletRequest request, HttpServletResponse response)throws Exception {
		String serial = request.getParameter(Parm.SERIAL);
		String a = request.getParameter(Parm.DC);
		Object obj = detailDAO.findBySerialDc(serial,Integer.parseInt(a), organDAO.getSonCodeList(cu_organCode(request)));
		
		if (null != obj) {
			Object[] comm = (Object[]) obj;
			Byte snc = null != comm[2] ? (Byte) comm[2] : null;
			String name = "";
			if (null !=  snc && snc.byteValue() == 1)
				name = "不需要序列号";
			else if (null !=  snc && snc.byteValue() == 2)
				name = "同类序列号";
			else
				name = "唯一序列号";
					
			StringBuffer result = new StringBuffer("{");
			
			result.append("\"cc\":\"" + comm[0] +"\",");
			result.append("\"cname\":\"" + comm[1] +"\",");
			result.append("\"snc\":\"" + comm[2] +"\",");
			result.append("\"s\":\"" + name +"\",");
			result.append("\"price\":\"" + comm[3] +"\",");
			result.append("\"serial\":\"" + comm[4] +"\",");
			result.append("\"dc\":\"" + comm[5] +"\",");
			result.append("\"dname\":\"" + comm[6] +"\",");
			result.append("\"count\":\"" + comm[7] +"\"");
			result.append("}");
			print(response, result.toString());
		} else {
			return;
		}
	}
	
	@Autowired
	public void setIsDAO(InvStorageDAO isDAO) {
		this.isDAO = isDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setDetailDAO(InvStorageDetailDAO detailDAO) {
		this.detailDAO = detailDAO;
	}
	@Autowired
	public void setIisDAO(InvInStorageDAO iisDAO) {
		this.iisDAO = iisDAO;
	}
	@Autowired
	public void setIisiDAO(InvInStorageItemDAO iisiDAO) {
		this.iisiDAO = iisiDAO;
	}
	@Autowired
	public void setIosDAO(InvOutStorageDAO iosDAO) {
		this.iosDAO = iosDAO;
	}
	@Autowired
	public void setIosiDAO(InvOutStorageItemDAO iosiDAO) {
		this.iosiDAO = iosiDAO;
	}
	@Autowired
	public void setIdDAO(InvDepotDAO idDAO) {
		this.idDAO = idDAO;
	}
	@Autowired
	public void setIisdDAO(InvInStorageDetailDAO iisdDAO) {
		this.iisdDAO = iisdDAO;
	}
	@Autowired
	public void setIbcfDAO(InvBillConfingDAO ibcfDAO) {
		this.ibcfDAO = ibcfDAO;
	}
	@Autowired
	public void setIaDAO(InvAllocateDAO iaDAO) {
		this.iaDAO = iaDAO;
	}
	@Autowired
	public void setIaiDAO(InvAllocateItemDAO iaiDAO) {
		this.iaiDAO = iaiDAO;
	}
	@Autowired
	public void setIadDAO(InvAllocateDetailDAO iadDAO) {
		this.iadDAO = iadDAO;
	}
	@Autowired
	public void setIosdDAO(InvOutStorageDetailDAO iosdDAO) {
		this.iosdDAO = iosdDAO;
	}
	
}
